<template>
  <div class="population-dashboard">


    <!-- 污染源分布环形图 -->
    <el-card shadow="hover" class="mb-6">
      <div slot="header" class="card-header">
        <h3 class="card-title">概况</h3>
      </div>
      <div class="chart-container">
        <div ref="populationTypeChart" class="chart" :style="{ width: '100%', height: '250px' }"></div>
      </div>
    </el-card>
    <el-card shadow="hover">
      <div slot="header" class="card-header">
        <h3 class="card-title">污染源在线监控最新达标率</h3>
      </div>
      <div class="dashboard-container">
        <!-- 左侧图表 -->
        <div class="chart-container left-chart">
          <div ref="distributionChart" class="chart" :style="{ width: '100%', height: '250px' }"></div>
        </div>
        <!-- 右侧指标 -->
        <div class="stats-container">
          <div class="stats-wrapper">
            <el-row class="stats-row">
              <el-col :span="12">
                <div class="stat-item">
                  <div class="stat-label">在线污染源</div>
                  <div class="stat-value">{{ monitoringCount }}</div>
                  <div class="stat-unit">家</div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="stat-item">
                  <div class="stat-label">达标率</div>
                  <div class="stat-value">{{ complianceRate }}</div>
                  <div class="stat-unit">%</div>
                </div>
              </el-col>
            </el-row>
            <el-row class="stats-row">
              <el-col :span="12">
                <div class="stat-item">
                  <div class="stat-label">污水处理厂</div>
                  <div class="stat-value">{{ treatmentPlantsCount }}</div>
                  <div class="stat-unit">家</div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="stat-item">
                  <div class="stat-label">超标排放</div>
                  <div class="stat-value">{{ exceedCount }}</div>
                  <div class="stat-unit">家</div>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
      </div>
    </el-card>
    <!-- 主要污染物及占比柱状图 -->
    <el-card shadow="hover">
      <div slot="header" class="card-header">
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <h3 class="card-title">主要污染物排放量</h3>
          <el-select v-model="selectedPollutant" placeholder="请选择污染物" size="small" style="width: 150px;"
            @change="handlePollutantChange">
            <el-option v-for="pollutant in pollutantOptions" :key="pollutant.value" :label="pollutant.label"
              :value="pollutant.value">
            </el-option>
          </el-select>
        </div>
      </div>

      <div class="chart-container pollutant-chart-container">
        <div ref="pollutantChart" class="chart" :style="{ width: '100%', height: '250px' }"></div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { pollutionsourceenterprisetype, enterprisemonitorrate, basPollutionsourcewrwpfl } from "../../api/pollution.js";
import * as echarts from 'echarts'



// const formatYear = (date) => {
//   return date.getFullYear().toString();
// };
// const formatMonth = (date) => {
//   return date.getFullYear() + '-' +
//     String(date.getMonth() + 1).padStart(2, '0');
// };

// 常量配置
const CONSTANTS = {
  // 图表相关样式配置
  CHART_STYLES: {
    TOOLTIP: {
      BACKGROUND: 'rgba(255, 255, 255, 0.9)',
      BORDER_COLOR: '#ddd',
      BORDER_WIDTH: 1,
      TEXT_COLOR: '#333'
    },
    AXIS: {
      LINE_COLOR: '#ccc',
      LABEL_COLOR: '#606266',
      SPLIT_LINE_COLOR: '#f0f0f0'
    },

  }
}
export default {
  name: 'PollutionSourcePanel',
  data() {
    return {
      // 图表实例
      populationTypeChart: null,
      pollutantChart: null,

      pollutionEnterpriseData: [],
      pollutionEnterpriseLengend: [],
      pollutionEnterpriseDatalabels: {},
      pollutantData: {},

      selectedPollutant: '',
      pollutantOptions: [

      ],
      monitoringCount: 0,     // 监控企业数
      complianceRate: 0,      // 达标率
      treatmentPlantsCount: 0, // 污水处理厂数
      exceedCount: 0
    }
  },
  computed: {

  },

  mounted() {
    this.getPollutionsourceenterprisetype()
    this.getComplianceRateData();
    this.getBasPollutionsourcewrwpfl()
    // 监听窗口大小变化，调整图表尺寸
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    // 清理事件监听和图表实例，防止内存泄漏
    window.removeEventListener('resize', this.handleResize)
    this.populationTypeChart?.dispose()
    this.pollutantChart?.dispose()
  },
  methods: {
    // 1. 生命周期相关方法
    handleResize() {
      this.populationTypeChart?.resize()
      this.pollutantChart?.resize()
    },

    // 2. 初始化图表方法（按视图顺序）
    initpollutionEnterpriseChart() {
      if (this.$refs.populationTypeChart) {
        this.populationTypeChart = echarts.init(this.$refs.populationTypeChart)
        this.populationTypeChart.setOption(this.getpollutionEnterpriseOption())
      }
    },

    initComplianceRateChart() {
      if (this.$refs.distributionChart) {
        const chart = echarts.init(this.$refs.distributionChart);
        chart.setOption(this.getComplianceRateOption());
      }
    },

    initPollutantChart() {
      if (this.pollutantChart) {
        this.pollutantChart.setOption(this.getPollutantOption())
      }
      else {
        if (this.$refs.pollutantChart) {
          this.pollutantChart = echarts.init(this.$refs.pollutantChart)
          this.pollutantChart.setOption(this.getPollutantOption())
        }
      }
    },

    // 3. 图表配置方法（按视图顺序）
    getpollutionEnterpriseOption() {
      const { TOOLTIP } = CONSTANTS.CHART_STYLES
      let pollutionEnterpriseDatalabels = this.pollutionEnterpriseDatalabels;
      return {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)',
          backgroundColor: TOOLTIP.BACKGROUND,
          borderColor: TOOLTIP.BORDER_COLOR,
          borderWidth: TOOLTIP.BORDER_WIDTH,
          textStyle: { color: TOOLTIP.TEXT_COLOR }
        },
        legend: {
          orient: 'vertical',
          right: '15%',
          top: 'center',
          data: this.pollutionEnterpriseLengend,
          formatter: function (type) {
            //console.log(pollutionEnterpriseDatalabels)
            //console.log(pollutionEnterpriseDatalabels[type])
            return pollutionEnterpriseDatalabels[type];
          },
          textStyle: { color: TOOLTIP.TEXT_COLOR },
          itemGap: 12
        },
        series: [
          {
            name: '污染源',
            type: 'pie',
            center: ['25%', '50%'],
            radius: ['40%', '70%'],
            itemStyle: {
              borderRadius: 4,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: { show: false },
            emphasis: {
              label: { show: true, fontSize: 16, fontWeight: 'bold', position: 'center' }
            },
            labelLine: { show: false },
            data: this.pollutionEnterpriseData
          }
        ]
      }
    },

    getComplianceRateOption() {
      return {
        // 提示框（鼠标悬停时显示）
        tooltip: {
          formatter: `${this.complianceRate}%`
        },
        series: [
          {
            type: 'pie',
            // 设置内外半径，形成圆环
            radius: ['70%', '90%'],
            // 禁止鼠标交互（可选）
            silent: true,
            // 起始角度设为90度，让圆环从顶部开始
            startAngle: 90,
            // 饼图的扇区是否是顺时针排布
            clockWise: true,
            // 数据项
            data: [
              {
                // 进度部分
                value: this.complianceRate,
                itemStyle: {
                  // 进度部分颜色，使用渐变色
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#4158D0' },
                    { offset: 0.5, color: '#C850C0' },
                    { offset: 1, color: '#FFCC70' }
                  ])
                }
              },
              {
                // 剩余部分
                value: 100 - this.complianceRate,
                itemStyle: {
                  // 剩余部分颜色（灰色背景）
                  color: '#e6e6e6'
                }
              }
            ],
            // 标签设置（显示进度文本）
            label: {
              show: true,
              position: 'center',
              // 文本样式
              formatter: [
                `{value|${this.complianceRate}%}`,
                '{name|完成率}'
              ].join('\n'),
              rich: {
                value: {
                  fontSize: 30,
                  fontWeight: 'bold',
                  color: '#333'
                },
                name: {
                  fontSize: 14,
                  color: '#666',
                  marginTop: 5
                }
              }
            },
            // 隐藏连接线
            labelLine: {
              show: false
            },
            // 动画效果
            animationDuration: 1000,
            animationEasing: 'cubicOut'
          }
        ]
      };
    },

    /**
     * 获取污染物图表配置（折线图）
     */
    getPollutantOption() {
      const { TOOLTIP, AXIS } = CONSTANTS.CHART_STYLES;

      let xAxisData = [];
      let lineData = [];

      // 判断是否有选中的污染物，并确保对应的数据是数组
      if (
        this.selectedPollutant &&
        this.pollutantData &&
        Array.isArray(this.pollutantData[this.selectedPollutant])
      ) {
        const data = this.pollutantData[this.selectedPollutant];
        data.forEach(item => {
          xAxisData.push(item.monitorTime);
          lineData.push(item.strength);
        });
      }

      return {
        tooltip: {
          trigger: 'axis',
          backgroundColor: TOOLTIP.BACKGROUND,
          borderColor: TOOLTIP.BORDER_COLOR,
          borderWidth: TOOLTIP.BORDER_WIDTH
        },
        legend: {
          data: [],
          top: 0,
          left: 'center'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
          top: 60
        },
        xAxis: {
          type: 'category',
          data: xAxisData,
          axisLine: { lineStyle: { color: AXIS.LINE_COLOR } },
          axisLabel: { color: AXIS.LABEL_COLOR }
        },
        yAxis: {
          type: 'value',
          axisLine: { lineStyle: { color: AXIS.LINE_COLOR } },
          axisLabel: { color: AXIS.LABEL_COLOR },
          splitLine: { lineStyle: { color: AXIS.SPLIT_LINE_COLOR } }
        },
        series: [{
          type: 'line',
          data: lineData,
          smooth: true,
          itemStyle: { color: '#409EFF' },
          lineStyle: { width: 2 },
          symbolSize: 6,
          symbol: 'circle',
          areaStyle: {
            opacity: 0.1
          }
        }]
      };
    },

    // 4. 数据获取方法（按调用顺序）
    getPollutionsourceenterprisetype() {
      pollutionsourceenterprisetype().then(res => {
        let data = res.data;
        data.forEach(element => {
          if (element.enterpriseTypeName == null) {
            element.enterpriseTypeName = '其他'
          }
          this.pollutionEnterpriseData.push({ value: element.enterpriseTypeSize, name: element.enterpriseTypeName })
          this.pollutionEnterpriseLengend.push(element.enterpriseTypeName)

          this.pollutionEnterpriseDatalabels[`${element.enterpriseTypeName}`] = `${element.enterpriseTypeName} ${element.enterpriseTypeSize}家 ${element.quantityProportion}%`
        });
        this.initpollutionEnterpriseChart()
      })
    },

    // getComplianceRateData() {
    //   // 调用API获取达标率数据
    //   enterprisemonitorrate({}).then(res => {
    //         this.monitoringCount = res.data.size;
    //        this.treatmentPlantsCount = res.data.wssize;
    //        this.exceedCount = res.data.cbsize;
    //          this.treatmentPlantsCount = res.data.wssize;
    //     if (res && res.data && res.data.dbl !== undefined && res.data.dbl !== null) {
    //       let rate = parseFloat(res.data.dbl);
    //       // 确保转换后的值是有效数字再进行赋值
    //       if (!isNaN(rate) && isFinite(rate)) {
    //         // rate = 39.05
    //         this.complianceRate = rate.toFixed(2);

    //       } else {
    //         console.warn('Invalid compliance rate value:', res.data.dbl);
    //         this.complianceRate = 0.00; // 设置默认值
    //       }
    //     } else {
    //       console.warn('Invalid response structure for compliance rate:', res);
    //       this.complianceRate = 0.00; // 设置默认值
    //     }
    //     this.initComplianceRateChart();
    //   }).catch(error => {
    //     // 添加错误处理，避免未捕获的异常
    //     console.error('Failed to fetch enterprise monitor rate:', error);
    //     this.complianceRate = '0.00'; // 设置默认值
    //     this.initComplianceRateChart();
    //   })
    // },
    getComplianceRateData() {
      // 调用API获取达标率数据
      enterprisemonitorrate({}).then(res => {
        if (!res || !res.data) {
          console.warn('Invalid response structure for compliance rate:', res);
          this.complianceRate = 0.00;
          return;
        }
    
        const { size = 0, wssize = 0, cbsize = 0, dbl } = res.data;
    
        this.monitoringCount = size;
        this.treatmentPlantsCount = wssize;
        this.exceedCount = cbsize;
    
        if (dbl !== undefined && dbl !== null) {
          let rate = parseFloat(dbl);
          if (!isNaN(rate) && isFinite(rate)) {
            this.complianceRate = parseFloat(rate.toFixed(2));
          } else {
            console.warn('Invalid compliance rate value:', dbl);
            this.complianceRate = 0.00;
          }
        } else {
          console.warn('Missing compliance rate field in response:', res);
          this.complianceRate = 0.00;
        }
      }).catch(error => {
        console.error('Failed to fetch enterprise monitor rate:', error);
        this.complianceRate = 0.00;
      }).finally(() => {
        this.initComplianceRateChart();
      });
    },
    getBasPollutionsourcewrwpfl() {
      this.loading = true;
      basPollutionsourcewrwpfl().then(res => {
        if (res && res.data && Array.isArray(res.data.list)) {
          const list = res.data.list;
          this.pollutantOptions = [];
          this.pollutantData = {};

          list.forEach((element, index) => {
            if (index == 0) {
              this.selectedPollutant = element.pollutantCode
            }
            // 构建选项数组
            this.pollutantOptions.push({
              value: element.pollutantCode,
              label: element.pollutantName
            });
            // 构建数据映射
            this.pollutantData[element.pollutantCode] = element.data;
          });
          this.initPollutantChart();
        }
      }).catch(error => {
        console.error('获取污染源数据失败:', error);
        this.$message.error('数据加载失败');
      }).finally(() => {
        this.loading = false;
      });
    },

    /**
   * 处理污染物选择变化
   */
    handlePollutantChange(value) {
      this.selectedPollutant = value;
      // 重新初始化污染物图表
      this.initPollutantChart();
    },
  }
}

</script>

<style scoped>
.population-dashboard {
  background-color: #f5f7fa;
  max-height: 100vh;
  padding: 5px;
  max-width: 100%;
  /* 移除或增加最大宽度限制 */
}
.card-header {
display: flex;
align-items: center;
}
.el-card__header {
  padding: 5px !important;
}
.card-title {
font-size: 18px;
font-weight: bold;
color: #333;
}

/* 添加新的容器样式 */
.population-dashboard {
  width: 100%;
  min-width: 500px;
  margin: 0 auto;
}

.chart-container {
  position: relative;
}


.dashboard-container {
  display: flex;
  flex-wrap: wrap;
 width: '100%';
 height: '250px'
}

.left-chart {
  flex: 1;
  width: 50%;
}

.stats-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-item {
  text-align: center;
  padding: 20px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

@media (max-width: 768px) {
  .dashboard-container {
    flex-direction: column;
  }

  .left-chart,
  .stats-container {
    min-width: 100%;
  }

  .el-col-xs-12 {
    width: 50% !important;
  }


}
</style>
